package com.skit.mine.fragment

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.alibaba.android.arouter.launcher.ARouter
import com.bumptech.glide.request.RequestOptions
import com.skit.common.base.BaseFragment
import com.skit.common.bean.User
import com.skit.common.config.RetrofitClient
import com.skit.common.config.RouteConfig
import com.skit.common.event.EventMessage
import com.skit.common.http.HttpUtils
import com.skit.common.ktx.NetResultKtx.init
import com.skit.common.manager.UserManager
import com.skit.common.retrofit.UserProtocol
import com.skit.common.utils.ToastUtils
import com.skit.mine.databinding.PersonFragmentMeBinding
import com.skit.mine.ui.MainActivity
import com.skit.mine.ui.UserInfoActivity
import com.skit.mine.viewmodel.ActivityNum
import com.skit.mine.viewmodel.PersonViewModel
import dagger.hilt.android.AndroidEntryPoint
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


/**
 * @author shuike <a href="mailto:shuike007@gmail.com">Contact me.</a>
 * @version 1.0
 * @since  2020/4/27
 */

@AndroidEntryPoint
class PersonFragment : BaseFragment() {

    private var rootView: View? = null

    //顶部状态栏高度padding
    override val statusPadding: Boolean = false
    private val requestOption = RequestOptions.circleCropTransform()
    private lateinit var binding: PersonFragmentMeBinding
    private val personViewModel: PersonViewModel by lazy {
        ViewModelProvider(this).get(
            PersonViewModel::class.java
        )
    }// by viewModels()

    private var user: User? = UserManager.user

    companion object {
        private const val TAG = "PersonFragment"
        fun newInstance(): PersonFragment {
            val fragment = PersonFragment()
            val bundle = Bundle()

            fragment.arguments = bundle
            return fragment
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = PersonFragmentMeBinding.inflate(inflater, container, false).apply {
            lifecycleOwner = viewLifecycleOwner
            viewModel = personViewModel
        }
        rootView = binding.root
        return rootView
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        personViewModel.loginClickListener.set(View.OnClickListener {
            //跳转到登录界面
            startActivity(Intent(activity, MainActivity::class.java))
        })
        binding.refreshLayout.setOnRefreshListener {
            initUser(UserManager.user)
//            lifecycleScope.launch(Dispatchers.IO) {
//                delay(3000)
//                withContext(Dispatchers.Main) {
//                    binding.refreshLayout.isRefreshing = false
//                }
//            }
        }

        binding.ibMyCollection.setOnClickListener {
            if (user != null) {
                ARouter.getInstance().build(RouteConfig.MainRoute.MAIN_USER_COLLECT_ACTIVITY)
                    .navigation()
            }
        }
    }

    override fun initConfig() {
        super.initConfig()
        personViewModel.userDataLiveData.observe(this, Observer {
            it.init({

            }, {
                personViewModel.setUser(data)
            })
        })
    }

    override fun initData() {
        super.initData()
        val user = UserManager.user
        personViewModel.setUser(user)
        initUser(user)
    }

    private fun initUser(user: User?) {
        binding.isAdmin = false
        if (user == null) {
            binding.apply {
                userName.text = "未登录"
                showLoginView()
                userName.setOnClickListener {
                    startActivity(Intent(activity, MainActivity::class.java))
                }
                userIcon.setOnClickListener {
                    startActivity(Intent(activity, MainActivity::class.java))
                }
                userTop.setOnClickListener {
                    startActivity(Intent(activity, MainActivity::class.java))
                }
                personViewModel.setActivityNums(ActivityNum())
                if (binding.refreshLayout.isRefreshing) binding.refreshLayout.isRefreshing = false
            }
        } else {
            binding.apply {

                userName.setOnClickListener {
                    startActivity(Intent(activity, UserInfoActivity::class.java))
                }
                userIcon.setOnClickListener {
                    startActivity(Intent(activity, UserInfoActivity::class.java))
                }

                userTop.setOnClickListener {
                    startActivity(Intent(activity, UserInfoActivity::class.java))
                }
            }
            initUser()
            personViewModel.getUserData(user.id, user.token)
        }
    }

    private fun initUser() {
        val service =
            RetrofitClient.getService(UserProtocol::class.java)
        val call = service.activityNum(UserManager.user?.id!!)
        HttpUtils.doRequest(call) {
            if (binding.refreshLayout.isRefreshing) binding.refreshLayout.isRefreshing =
                false
            if (it == null || !it.isSuccess) {
                if (it != null) ToastUtils.showToast(it.msg)
                return@doRequest
            }
            activityNumData(it.data)
        }
        user?.let {
            personViewModel.getUserData(it.id, it.token)
        }
        val adminCall =
            service.isAdmin(UserManager.user?.id!!, UserManager.user?.token!!)
        HttpUtils.doRequest(adminCall) {
            if (it == null || !it.isSuccess) {
                if (it != null) ToastUtils.showToast(it.msg)
                return@doRequest
            }
            binding.isAdmin = it.data
            binding.admin.setOnClickListener {
                ARouter.getInstance().build(RouteConfig.AdminRoute.MAIN_ACTIVITY)
                    .navigation()
            }
        }
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        binding.setting.setOnClickListener {
            ARouter.getInstance().build(RouteConfig.AppRoute.SETTING_ACTIVITY).navigation()
        }
    }

    override fun onResume() {
        super.onResume()
        Log.d(TAG, "onResume: ")
        initUser(UserManager.user)
    }

    /*   fun user() {
           user = UserManager.user
           personViewModel.setUser(user)
           binding.isAdmin = false
           binding.apply {
               if (user == null) {
                   userName.text = "未登录"
                   showLoginView()
                   userName.setOnClickListener {
                       startActivity(Intent(activity, MainActivity::class.java))
                   }
                   userIcon.setOnClickListener {
                       startActivity(Intent(activity, MainActivity::class.java))
                   }
                   userTop.setOnClickListener {
                       startActivity(Intent(activity, MainActivity::class.java))
                   }
                   personViewModel.setActivityNums(ActivityNum())
                   if (binding.refreshLayout.isRefreshing) binding.refreshLayout.isRefreshing = false
               } else {
   //            personViewModel.setUser(user)
                   userName.setOnClickListener {
                       startActivity(Intent(activity, UserInfoActivity::class.java))
                   }
                   userIcon.setOnClickListener {
                       startActivity(Intent(activity, UserInfoActivity::class.java))
                   }

                   userTop.setOnClickListener {
                       startActivity(Intent(activity, UserInfoActivity::class.java))
                   }

                   val service =
                       RetrofitClient.getService(UserProtocol::class.java)
                   val call = service.activityNum(UserManager.user?.id!!)
                   HttpUtils.doRequest(call) {
                       if (binding.refreshLayout.isRefreshing) binding.refreshLayout.isRefreshing =
                           false
                       if (it == null || !it.isSuccess) {
                           if (it != null) ToastUtils.showToast(it.msg)
                           return@doRequest
                       }
                       activityNumData(it.data)
                   }
                   user?.let {
                       viewModel.getUserData(it.id, it.token)
                   }
                   val adminCall =
                       service.isAdmin(UserManager.user?.id!!, UserManager.user?.token!!)
                   HttpUtils.doRequest(adminCall) {
                       if (it == null || !it.isSuccess) {
                           if (it != null) ToastUtils.showToast(it.msg)
                           return@doRequest
                       }
                       binding.isAdmin = it.data
                       admin.setOnClickListener {
                           ARouter.getInstance().build(RouteConfig.AdminRoute.MAIN_ACTIVITY)
                               .navigation()
                       }
                   }

               }

           }
       }

   */
//    private fun getData(user: User) {
//        val userProtocol = RetrofitClient.getService(UserProtocol::class.java)
//        val userInfo =
//            userProtocol.getUserInfo(user.id, user.token)
//        doRequest<User>(userInfo,
//            object : RequestFinishCallback<User> {
//                override fun getRequest(result: StatusResult<User>?) {
//                    if (result == null || !result.isSuccess) {
//                        if (result != null) {
//                            if (result.status == 401) {
//                                UserManager.logout()
//                                user()
//                            }
//                            ToastUtils.showToast(result.msg)
//                        }
//                        return
//                    }
//                    val data = result.data
//                    if (data != null) {
//                        this@PersonFragment.user = data
////                        saveUser(data)
////                        setData(data)
//                    }
//                }
//            }
//        )
//    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    override fun event(eventMessage: EventMessage) {
        super.event(eventMessage)
        if (eventMessage.code == EventMessage.MessageCode.LOGOUT) {
            initUser(null)
            if (eventMessage.code == EventMessage.MessageCode.LOGOUT) {
                personViewModel.setUser(null)
            }
        }
    }

    private fun activityNumData(data: Map<String, Int>) {
        val i = data["daishenhe"]
        val i1 = data["daikaishi"]
        val i2 = data["jinxingzhong"]
        val i3 = data["quanbu"]
        personViewModel.setActivityNums(ActivityNum(i, i1, i2, i3))
    }

    private fun showLoginView() {

    }

}